package com.blackink.controller;

import com.blackink.service.UserService;
import com.blackink.tool.BaseController;
import com.blackink.tool.CustomResult;
import com.blackink.tool.HttpUtil;
import com.blackink.tool.UpdateException;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;


@Controller
public class LoginController extends BaseController {

    private String SHIRO_VERIFY_SESSION = "verifySessionCode";

    @Autowired
    UserService userService;


    @RequestMapping(value = "/login",method = RequestMethod.GET)
    public String toLogin(){
        return "login";
    }

    @ResponseBody
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public CustomResult login(String username, String password, String captcha, HttpServletRequest request){
        UsernamePasswordToken token = new UsernamePasswordToken(username,password);
        Subject subject = SecurityUtils.getSubject();
        String code = (String) subject.getSession().getAttribute(SHIRO_VERIFY_SESSION);
        if (code == null){
            return CustomResult.error("验证码异常");
        }else if ("".equals(captcha) || (!code.equals(captcha))){
            return CustomResult.error("验证码错误");
        }
        try {
            subject.login(token);
            userService.loginUpdate(token.getUsername(), HttpUtil.getIpAddr(request));
            return CustomResult.success();
        }catch (AuthenticationException e){
            return CustomResult.error("用户或密码错误");
        }catch (UpdateException e){
            subject.logout();
            return CustomResult.error(e.getMessage());
        }
    }



}
